<template>
  <div
    v-loading="addLoading"
    class="group-layout"
    element-loading-text="正在创建中,请稍后"
    element-loading-spinner="el-icon-loading"
    style="margin-bottom: 24px"
  >
    <el-card class="card-box" shadow="never">
      <el-image v-if="appInfo.icon" class="img" :src="appInfo.icon">
        <div slot="error" class="image-slot">
          <i class="iconfont icon-a-Vector1"></i>
        </div>
      </el-image>
      <div class="before-set">
        <p v-if="appInfo.appName" class="app-name">{{ appInfo.appName }}</p>
        <p class="app-adress">
          <span class="">结算币种：</span>
          <span>
            {{ $store.state.user.unit === "USD" ? "美元" : "人民币" }}
          </span>
        </p>
        <p>{{ uuAndOrgName || "--" }}</p>
        <p class="series-position">
          <span>投放位置：</span>
          <span>{{
            campaignForm.adChannelType == "SEARCH" ? "搜索结果" : '"搜索"标签'
          }}</span>
        </p>
        <p v-if="campaignForm.countriesOrRegions.length" class="app-adress">
          <span class="">投放地区：</span>
          <span v-if="campaignForm.countriesOrRegions.length > 1">{{
            campaignForm.countriesOrRegions.length
          }}</span>
          <span v-else>{{ campaignForm.countriesOrRegions[0] }}</span>
        </p>

        <p class="day-budget">
          <span class="">每日预算：</span>
          <span v-if="!campaignForm.dailyBudgetAmountNub">未设置</span>
          <span v-else>{{
            campaignForm.dailyBudgetAmountNub | $toFixed(2)
          }}</span>
        </p>
        <p v-if="campaignForm.adChannelType == 'SEARCH'" class="block">
          <span class="">广告计划屏蔽词：</span>
          <span>{{ campaignNegativeKeyword.length || 0 }}个</span>
        </p>
      </div>
    </el-card>
    <div
      :style="{
        position: 'relative',
        paddingRight: $route.query.create === 'addGroup' ? '0px' : '232px',
      }"
    >
      <el-card
        v-loading="loading"
        element-loading-text="正在创建中,请勿离开"
        shadow="never"
      >
        <div class="set-box">
          <cell-header title="广告组设置" style="padding-bottom: 24px" />
          <div class="group-form">
            <el-form
              ref="adGroupForm1"
              :model="adGroupForm"
              :rules="adGroupRules"
              label-position="top"
              class="demo-ruleForm"
              size="small"
            >
              <el-form-item label="广告组名称" prop="name">
                <el-input
                  v-model="adGroupForm.name"
                  placeholder="请输入广告组名称"
                  @input="onInput"
                />
              </el-form-item>

              <el-form-item
                v-if="campaignForm.adChannelType !== 'SEARCH'"
                prop="defaultBidAmountNub"
              >
                <div slot-name="label" class="label">
                  <span>每千次点击费用出价上限</span>
                  <el-popover
                    placement="top-start"
                    title="每千次展示费用出价上限"
                    width="300"
                    trigger="hover"
                    content="这是你在 App Store 上针对每一千次广告展示次数愿意支付的最高金额。每当至少有 50% 的广告在一秒钟内被浏览时，就计为一次展示。"
                  >
                    <i
                      slot="reference"
                      class="el-icon-question"
                      style="margin-left: 6px"
                    />
                  </el-popover>
                </div>

                <amountInput
                  v-model="adGroupForm.defaultBidAmountNub"
                  :controls="false"
                  :precision="2"
                  placeholder="请输入默认最高每次点击费用出价"
                />
              </el-form-item>

              <template v-else>
                <el-form-item prop="defaultBidAmountNub">
                  <div slot-name="label" class="label">
                    <span>默认每次最高点击费用出价</span>
                    <el-popover
                      placement="top-start"
                      title="默认最高点击费用出价"
                      width="300"
                      trigger="hover"
                      content="这是你愿意为每次广告点击支付的最高金额。此出价将适用于此广告组中的所有关键词，除非你申请了一个单独的关键词出价。"
                    >
                      <i
                        slot="reference"
                        class="iconfont icon-question-circle"
                        style="font-weight: 400; margin-left: -8px"
                      />
                    </el-popover>
                  </div>

                  <amountInput
                    v-model="adGroupForm.defaultBidAmountNub"
                    :controls="false"
                    :precision="2"
                    placeholder="请输入默认最高每次点击费用出价"
                  />
                </el-form-item>
                <el-form-item prop="cpaGoalNub">
                  <div slot-name="label" class="label">
                    <span>目标下载单价CPA(可选)</span>

                    <el-popover
                      placement="top-start"
                      title="目标下载单价"
                      width="300"
                      trigger="hover"
                      content="每次转化费用目标是你愿意为转化花费的金额。设置每次转化费用目标完全为可选项。"
                    >
                      <i
                        slot="reference"
                        class="iconfont icon-question-circle"
                        style="font-weight: 400; margin-left: 8px"
                      />
                    </el-popover>
                  </div>
                  <amountInput
                    v-model.number="adGroupForm.cpaGoalNub"
                    :controls="false"
                    :precision="2"
                    placeholder="请输入"
                  />
                </el-form-item>
                <el-form-item>
                  <div class="automatch">
                    <div class="label">
                      <span>自动将我的广告与相关搜索匹配</span>
                      <el-popover
                        placement="top-start"
                        title="搜索匹配"
                        width="300"
                        trigger="hover"
                        content="搜索匹配使用多种资源将你的广告与 App Store 中的相关搜索进行自动匹配，其中包括你的 App Store 列表中的元数据、同一类型中类似 app 的相关信息以及其他搜索数据"
                      >
                        <i
                          slot="reference"
                          class="iconfont icon-question-circle"
                          style="font-weight: 400; margin-left: 8px"
                        />
                      </el-popover>
                    </div>
                    <el-switch
                      v-model="adGroupForm.automatedKeywordsOptIn"
                      active-color="#24BEBE"
                    />
                  </div>
                </el-form-item>
              </template>
            </el-form>
          </div>
        </div>
        <div class="set-box">
          <cell-header
            v-if="campaignForm.adChannelType == 'SEARCH'"
            title="关键词"
            style="margin-top: 5px; padding-bottom: 24px"
          />
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            label-position="top"
            class="demo-ruleForm"
            size="small"
          >
            <template v-if="campaignForm.adChannelType == 'SEARCH'">
              <el-form-item prop="pass">
                <div slot-name="label" class="label">
                  <span>投放关键词</span>
                  <el-popover
                    placement="top-start"
                    title="关键词定位"
                    width="300"
                    trigger="hover"
                    content="通过此功能，你可以为广告系列添加关键词。对任何关键词单独出价，以优化投资回报。广泛匹配自动包含同义词、包含该术语的短语，以及常见拼写错误的词和复数，因此你无需添加这些。"
                  >
                    <i
                      slot="reference"
                      class="iconfont icon-question-circle"
                      style="font-weight: 400; margin-left: 8px"
                    />
                  </el-popover>
                </div>
                <el-button
                  v-show="!keywords.length"
                  class="add-btn"
                  size="small"
                  @click="putShow = true"
                >
                  <span style="font-size: 14px">添加</span>
                </el-button>

                <el-button
                  v-show="keywords.length"
                  class="add-btn"
                  size="small"
                  style="margin-left: 0px"
                  @click="putShow = true"
                >
                  <p class="flex">
                    <span style="font-size: 14px"
                      >已添加{{ keywords.length }}个投放关键词</span
                    >
                    <span><em style="font-size: 14px">添加</em></span>
                  </p>
                </el-button>
              </el-form-item>
              <el-form-item prop="checkPass">
                <div slot-name="label" class="label">
                  <span>屏蔽关键词</span>
                  <el-popover
                    placement="top-start"
                    title="屏蔽关键词"
                    width="300"
                    trigger="hover"
                    content="否定关键词可防止你的广告在这些词的搜索结果中显示。"
                  >
                    <i
                      slot="reference"
                      class="iconfont icon-question-circle"
                      style="font-weight: 400; margin-left: 8px"
                    />
                  </el-popover>
                </div>
                <el-button
                  v-show="!negativeKeyword.length"
                  class="add-btn"
                  size="small"
                  @click="balckShow = true"
                >
                  <span style="font-size: 14px">添加</span>
                </el-button>
                <el-button
                  v-show="negativeKeyword.length"
                  class="add-btn"
                  size="small"
                  style="margin-left: 0px"
                  @click="balckShow = true"
                >
                  <p class="flex">
                    <span style="font-size: 14px"
                      >已添加{{ negativeKeyword.length }}个屏蔽关键词</span
                    >
                    <span><em style="font-size: 14px">添加</em></span>
                  </p>
                </el-button>
              </el-form-item>
            </template>

            <!-- 受众 -->
            <el-form-item>
              <el-collapse accordion class="shou-zhong-box">
                <el-collapse-item style="padding-top: 10px">
                  <template slot="title">
                    <div
                      slot-name="label"
                      class="label"
                      style="padding-bottom: 0px"
                      @click="audiencesShow = true"
                    >
                      <span>受众</span>
                      <!-- <i class="el-icon-caret-right" style="color: #474747;" /> -->
                    </div>
                  </template>

                  <div style="height: 12px; width: 1px" />
                  <!-- 设备 -->
                  <el-form-item label="设备" style="padding-top: 12px">
                    <el-select
                      v-model="targeForm.deviceClassStr"
                      placeholder="iPad和iphone"
                    >
                      <el-option
                        v-for="item in deviceList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                      <!-- 到时候还要转换成数组 -->
                    </el-select>
                  </el-form-item>

                  <!-- 用户 -->
                  <el-form-item label="用户">
                    <el-select
                      v-model="targeForm.appDownloadersStr"
                      placeholder="所用用户"
                    >
                      <el-option label="所有用户" value="all" />
                      <el-option label="新用户" value="new" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="特征">
                    <el-row :gutter="14">
                      <el-col :span="12">
                        <el-select
                          v-model="targeForm.genderStr"
                          placeholder="所有性别"
                        >
                          <el-option label="所有性别" value="F,M" />
                          <el-option label="男性" value="M" />
                          <el-option label="女性" value="F" />
                        </el-select>
                        <!-- 到时候还要转换成数组 -->
                      </el-col>
                      <el-col :span="12">
                        <el-row :gutter="12">
                          <el-col :span="12">
                            <!-- 开始年龄 -->
                            <el-select
                              v-model="targeForm.minMaxAge.minAge"
                              placeholder="请选择最小年龄"
                            >
                              <el-option
                                v-for="item in ageList"
                                v-show="item.val * 1 !== 65"
                                :label="item.name"
                                :value="item.val"
                                :disabled="
                                  item.val > targeForm.minMaxAge.maxAge &&
                                  item.val !== 'all'
                                "
                              />
                            </el-select>
                          </el-col>

                          <el-col
                            v-if="
                              targeForm.minMaxAge.minAge !== 'all' &&
                              targeForm.minMaxAge.minAge !== 65
                            "
                            :span="12"
                          >
                            <!-- 结束年龄 -->
                            <el-select
                              v-model="targeForm.minMaxAge.maxAge"
                              placeholder="请选择最大年龄"
                            >
                              <template v-for="item in ageList">
                                <el-option
                                  v-if="item.val !== 'all'"
                                  :label="item.name"
                                  :value="item.val"
                                  :disabled="
                                    item.val < targeForm.minMaxAge.minAge
                                  "
                                />
                              </template>
                            </el-select>
                          </el-col>
                        </el-row>
                      </el-col>
                    </el-row>
                  </el-form-item>

                  <el-form-item
                    :label="
                      countriesOrRegionsDisable
                        ? '目标地理位置(不可用)'
                        : '目标地理位置'
                    "
                  >
                    <el-select
                      v-model="locVal"
                      :placeholder="countriesOrRegionsDisableText"
                      :disabled="countriesOrRegionsDisable"
                      multiple
                      filterable
                      remote
                      :remote-method="getLocation"
                      @change="handleLocChange"
                    >
                      <el-option
                        v-for="item in locList"
                        :key="item.displayname"
                        :label="item.displayname"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item
                    :label="
                      timeZone === 'UTC'
                        ? '广告投放时间设置(UTC时间)'
                        : '广告投放时间设置(亚洲/上海时间)'
                    "
                    prop="startTime"
                    class="timeBox"
                    :style="{
                      marginBottom:
                        campaignForm.adChannelType == 'SEARCH' ? '30px' : '0px',
                    }"
                  >
                    <el-row :gutter="14">
                      <el-col :span="24">
                        <p style="font-size: 14px; padding-bottom: 6px">
                          开始时间
                        </p>
                        <el-col :span="12">
                          <el-date-picker
                            v-model="adGroupForm.startTime"
                            style="margin-left: -7px"
                            type="datetime"
                            placeholder="选择开始时间"
                            format="yyyy-MM-dd HH:mm"
                            value-format="yyyy-MM-dd HH:mm"
                            :picker-options="startTimeDay"
                            :clearable="false"
                          />
                        </el-col>
                      </el-col>

                      <el-col :span="24">
                        <p style="padding-top: 10px; padding-bottom: 6px">
                          <el-checkbox v-model="endTimeShow"
                            >结束时间(可选)</el-checkbox
                          >
                        </p>
                        <el-col v-show="endTimeShow" :span="24">
                          <el-col :span="12">
                            <el-date-picker
                              v-model="adGroupForm.endTime"
                              style="margin-left: -12px"
                              type="datetime"
                              placeholder="选择结束时间"
                              format="yyyy-MM-dd HH:mm"
                              value-format="yyyy-MM-dd HH:mm"
                              :picker-options="endTimeDay"
                              :clearable="false"
                            />
                          </el-col>
                        </el-col>
                      </el-col>
                    </el-row>
                  </el-form-item>
                  <el-form-item
                    v-if="campaignForm.adChannelType === 'SEARCH'"
                    label="分时段(可选)"
                    style="margin-bottom: 0px"
                  >
                    <div class="day-prt-box">
                      <day-parting v-model="targeForm.daypartInt"></day-parting>
                      <!-- <day-parting-box ref="daypartBox" :checked-time="targeForm.daypartInt" /> -->
                    </div>
                  </el-form-item>
                </el-collapse-item>
              </el-collapse>
            </el-form-item>

            <!-- 广告素材 -->
            <!-- <el-form-item>
              <div slot-name="label" class="label">
                <span>广告素材</span>
                <el-popover
                  placement="top-start"
                  title="广告素材"
                  width="300"
                  trigger="hover"
                  content="系统会使用你的App Store Connect 账户中的元数据、屏幕和app预览创建广告。"
                >
                  <i
                    slot="reference"
                    class="iconfont icon-question-circle"
                    style="font-weight: 400; margin-left: 8px"
                  />
                </el-popover>
              </div>
              <div class="sc_content">
                <div class="sc_content_flex">
                  <div class="sc_content_div">
                    <div class="sc_content_div_select">
                      <p>默认产品页面</p>
                      <p>使用默认App Store 产品页面中的素材资源。</p>
                    </div>
                    <div class="sc_content_div_select">
                      <p>自定义</p>
                      <p>使用默App Store Connect中自定产品页面里的素材资源。</p>
                    </div>
                    <div>
                      <p>默认产品页面</p>
                      <div style="display: flex">
                        <p>设备</p>
                        <el-dropdown
                          @command="chooseDevice"
                          style="
                            position: absolute;
                            right: 0;
                            margin-right: 120px;
                          "
                        >
                          <span class="el-dropdown-link">
                            iPhone<i
                              class="el-icon-arrow-down el-icon--right"
                            ></i>
                          </span>
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="iPhone"
                              >iPhone</el-dropdown-item
                            >
                            <el-dropdown-item command="iPad"
                              >iPad</el-dropdown-item
                            >
                          </el-dropdown-menu>
                        </el-dropdown>
                      </div>
                      <div style="display: flex">
                        <p>显示类型</p>
                        <el-dropdown
                          @command="chooseDevice"
                          style="
                            position: absolute;
                            right: 0;
                            margin-right: 120px;
                          "
                        >
                          <span class="el-dropdown-link">
                            图像<i
                              class="el-icon-arrow-down el-icon--right"
                            ></i>
                          </span>
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="图像"
                              >图像</el-dropdown-item
                            >
                            <el-dropdown-item command="文本"
                              >文本</el-dropdown-item
                            >
                          </el-dropdown-menu>
                        </el-dropdown>
                      </div>
                      <div style="display: flex">
                        <p>语言</p>
                        <el-dropdown
                          @command="chooseDevice"
                          style="
                            position: absolute;
                            right: 0;
                            margin-right: 120px;
                          "
                          disabled="true"
                        >
                          <span class="el-dropdown-link">
                            英语（美国）<i
                              class="el-icon-arrow-down el-icon--right"
                            ></i>
                          </span>
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="图像"
                              >图像</el-dropdown-item
                            >
                            <el-dropdown-item command="文本"
                              >文本</el-dropdown-item
                            >
                          </el-dropdown-menu>
                        </el-dropdown>
                      </div>
                    </div>
                  </div>
                  <div class="sc_content_div_right">
                    <img
                      src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                      alt=""
                      style="margin-left: 30px"
                    />
                    <h3>14个自定义产品页面可以使用。</h3>
                    <p>点击“创建广告”按钮，即可从你的自定义产品页面</p>
                    <p>选项中进行选择，并查看广告预览。</p>
                    <el-button type="success" size="small" @click="createGroup">创建广告</el-button>
                  </div>
                </div>
              </div>
              <div style="dispaly: block; width: 900px">
                如果你测试的是其他app图标，则此处的预览可能会有所不同。评级和价格并不反映实际数值。本预览不包括预定标签。
              </div>
            </el-form-item> -->
            <el-form-item
              v-if="$route.query.create === 'addGroup'"
              style="margin-top: 40px"
            >
              <el-button size="small" class="defult" @click="goToBefore"
                >返回</el-button
              >
              <el-button
                type="success"
                size="small"
                class="defult"
                @click="handSubAddGroup"
                >创建</el-button
              >
            </el-form-item>

            <el-form-item v-else style="margin-top: 40px">
              <el-button size="small" class="defult" @click="goToBefore"
                >上一步</el-button
              >
              <el-button
                type="success"
                size="small"
                class="defult"
                style="margin-left: 24px"
                @click="goToNext"
                >下一步</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <!-- {{campaignForm}} -->
        <!-- 关键词的最高点击出价不能超过广告系列的每日预算 -->
        <word-box
          ref="keyWordBox"
          :visible.sync="putShow"
          :max-num="
            campaignForm.dailyBudgetAmountNub
              ? campaignForm.dailyBudgetAmountNub
              : campaignForm.budgetAmountNub
          "
          :default-num="
            adGroupForm.defaultBidAmountNub
              ? adGroupForm.defaultBidAmountNub * 1
              : 0.01
          "
          title="投放关键词"
          :fei-yong-show="true"
          :words-list="keywords"
          :appid="campaignForm.adamId"
          width="1200px"
          :country-list="campaignForm.countriesOrRegions"
          @handleSub="handleSubKey"
        >
        </word-box>

        <word-box
          :visible.sync="balckShow"
          title="屏蔽关键词"
          :words-list="negativeKeyword"
          @handleSub="handleSubNegKey"
        />
      </el-card>
      <slot />
    </div>
    <!-- 创建自定义页面 -->
    <el-dialog
      title="创建广告"
      :visible.sync="createGroupShow"
      width="800px"
      :before-close="handleClose"
    >
      <createGroup></createGroup>
    </el-dialog>
  </div>
</template>

<script>
import wordBox from "@/components/word-box.vue";
import cellHeader from "@/components/cell-header.vue";
import dayParting from "@/components/dayParting/index.vue";
import amountInput from "@/components/amountInput/index.vue";
import recommendWord from "@/components/recommendWord/index.vue";
import createGroup from "./createGroupDia.vue";
import dayjs from "dayjs";
const moment = dayjs;
var utc = require("dayjs/plugin/utc");
moment.extend(utc);
import {
  sendAdvInfo,
  CreateCustomer,
  searchApps,
  adgroupIsEmptyName,
  addGroups,
  getSearchGeolocations,
} from "@/api/create.js";
export default {
  name: "CreateGroup",
  components: {
    wordBox,
    cellHeader,
    dayParting,
    amountInput,
    recommendWord,
    createGroup,
  },
  data() {
    // 验证广告组名称重复
    const validateName = async (rule, value, callback) => {
      if (this.campaignForm.campaignId) {
        const obj = {
          adGroupName: value,
          orgId: "", // 自助投放为空
          campaignId: this.$route.query.campaignId,
          currencyType:
            this.$route.query.currencyType || this.$store.state.user.unit,
          teamId: this.$store.state.team.teamId || "",
        };
        const res = await adgroupIsEmptyName(obj);
        if (res.data.code) {
          if (res.data.data && res.data.data.length) {
            callback(new Error("广告组名称重复"));
          } else {
            callback();
          }
        } else {
          callback(new Error("服务器出现错误，请稍后重试"));
        }
      } else {
        callback();
      }
    };

    // 验证最高出价 ||每千次展示费用出价上限
    const validateDefaultBidAmountNub = (rule, value, callback) => {
      const str =
        this.campaignForm.adChannelType === "SEARCH"
          ? "最高出价"
          : "每千次展示费用出价上限";
      const maxNum = this.campaignForm.dailyBudgetAmountNub
        ? this.campaignForm.dailyBudgetAmountNub
        : this.campaignForm.budgetAmountNub * 1;
      const maxTxt = this.campaignForm.dailyBudgetAmountNub
        ? "日预算"
        : "总预算";
      if (value * 100 < 1 || value > 1000) {
        callback(new Error(str + "必须至少为 0.01且不得高于1000.00"));
      } else if (value > maxNum) {
        callback(
          new Error(str + "不能大于广告系列" + maxTxt + maxNum.toFixed(2))
        );
      } else {
        callback();
      }
    };
    /* 目标下载单价 */
    const validateCpaGoal = (rule, value, callback) => {
      const maxNum = this.campaignForm.dailyBudgetAmountNub
        ? this.campaignForm.dailyBudgetAmountNub
        : this.campaignForm.budgetAmountNub * 1;
      const maxTxt = this.campaignForm.dailyBudgetAmountNub
        ? "日预算"
        : "总预算";
      if (
        this.adGroupForm.cpaGoalNub === undefined ||
        this.adGroupForm.cpaGoalNub === "" ||
        this.adGroupForm.cpaGoalNub === null
      ) {
        callback();
      } else if (value * 100 < 1 || value > 1500) {
        callback(
          new Error("你的每次转化费用目标必须至少为 0.01且不得高于1500.00")
        );
      } else if (value > maxNum) {
        callback(
          new Error(
            "你的每次转化费用目标不能大于广告系列" + maxTxt + maxNum.toFixed(2)
          )
        );
      } else {
        callback();
      }
    };
    return {
      createGroupShow: false,
      addLoading: false,
      campaignForm: {
        countriesOrRegions: [],
      }, // 上一步广告系列设置的内容
      appInfo: {}, // 上一步广告性选中的app
      campaignNegativeKeyword: [], // 广告系列屏蔽词
      startTimeDay: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8 * 1000 * 3600 - 8.64e7;
        },
      },

      endTimeDay: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8 * 1000 * 3600 - 8.64e7;
        },
      },

      loading: false,
      ageList: [
        {
          name: "不限年龄段",
          val: "all",
        },
      ],

      deviceList: [
        {
          label: "仅限iPad",
          value: "IPAD",
        },
        {
          label: "仅限iPhone",
          value: "IPHONE",
        },
        {
          label: "iPad 和 iPhone",
          value: "IPAD,IPHONE",
        },
      ],

      endTimeShow: false, // 是否显示结束时间
      startTime: {
        day: undefined,
        time: undefined,
      },
      endTime: {
        day: undefined,
        time: undefined,
      },

      adGroupForm: {
        // 广告组设置表单
        automatedKeywordsOptIn: false, // 自动匹配
        cpaGoalNub: undefined, // 目标下载单价
        defaultBidAmountNub: undefined, // 默认点击最大出价
        // amount*	string        currency*	string
        //    金额              货币类型，目前写死USD
        name: "", // 广告组名称
        startTime: undefined, // 开始时间
        endTime: undefined, // 结束时间
      },

      targeForm: {
        // 受众表单
        appDownloadersStr: "all", //	如果填写当前app的appid，就代表只允许新用户下载，不然到时候就为空
        minMaxAge: {
          // 年龄
          minAge: "all", // 最小年龄
          maxAge: 65, // 最大年龄
        },
        deviceClassStr: "IPAD,IPHONE", // 设备 到时候要转换成数组
        genderStr: "F,M", // 性别   到时候要转换成数组
        daypartInt: [], // 投放时间  分时段
        localArr: [],
      },
      keywords: [], // 投放关键词
      negativeKeyword: [], // 屏蔽关键词
      // 规则
      adGroupRules: {
        name: [
          {
            required: true,
            message: "请输入广告组名称",
            trigger: "blur",
          },
          {
            validator: validateName,
            trigger: "blur",
          },
        ],
        defaultBidAmountNub: [
          {
            required: true,
            message: "你的预算必须至少为 0.01",
            trigger: "blur",
          },
          {
            validator: validateDefaultBidAmountNub,
            trigger: "blur",
          },
        ],

        cpaGoalNub: [
          {
            validator: validateCpaGoal,
            trigger: "blur",
          },
        ],
      },
      countriesOrRegionsDisableText: "待验证，暂不可用",
      countriesOrRegionsDisable: true, // 地理位置不能点击
      putShow: false,
      balckShow: false,
      locVal: undefined,
      locList: [],
    };
  },
  computed: {
    timeZone() {
      return this.$store.state.user.timeZone;
    },
    uuAndOrgName() {
      if (this.campaignForm.uuAndOrgId) {
        let nameStr = "";
        const index = this.$store.state.overview.allAc.findIndex((item) => {
          return item.uuid == this.campaignForm.uuAndOrgId[0];
        });
        nameStr = this.$store.state.overview.allAc[index].secretName;
        const i = this.$store.state.overview.allAc[index].org.findIndex(
          (item) => {
            return item.orgId == this.campaignForm.uuAndOrgId[1];
          }
        );
        return (
          nameStr + "/" + this.$store.state.overview.allAc[index].org[i].orgName
        );
      } else {
        return " --";
      }
    },
  },

  watch: {
    campaignForm: async function (newVal, oldVal) {
      if (
        !this.campaignForm.countriesOrRegions.length ||
        this.campaignForm.countriesOrRegions.length > 1
      ) {
        this.countriesOrRegionsDisable = true;
        this.countriesOrRegionsDisableText =
          "如果你的广告系列是针对多个国家和地区设置的，则不可用";
      } else {
        const res = await getSearchGeolocations({
          country: this.campaignForm.countriesOrRegions[0],
          search: "",
        });

        if (res.data.code === 20000 && res.data.data.length) {
          this.countriesOrRegionsDisable = false;
          this.countriesOrRegionsDisableText = "请选择";
        } else {
          this.countriesOrRegionsDisable = true;
          this.countriesOrRegionsDisableText =
            "地理位置细分在此国家或地区不可用";
        }
      }
    },
  },

  // 离开此页面的时候缓存数据
  beforeRouteLeave(to, form, next) {
    if (to.name === "CreatePut" || to.name === form.name) {
      // 如果是去支付的页面  就把选中的数据存起来;
      const obj = {
        negativeKeyword: this.negativeKeyword,
        keywords: this.keywords,
        targeForm: this.targeForm,
        adGroupForm: this.adGroupForm,
        endTimeShow: this.endTimeShow,
      };
      localStorage.setItem("group-DATA", JSON.stringify(obj));
    } else {
      localStorage.removeItem("group-DATA");
      // 如果不是就把选择的数据删除掉
    }
    if (this.$route.create === "addGroup") {
      localStorage.removeItem("series-DATA");
    }

    next();
  },
  mounted() {
    // 循环出年龄段可选项目
    // 循环出年龄段可选项目
    for (let i = 18; i < 66; i++) {
      const obj = {
        name: i,
        val: i,
      };
      if (i === 65) {
        obj.name = "65+";
      }
      this.ageList.push(obj);
    }
    let obj;
    if (localStorage.getItem("series-DATA")) {
      // 获取campaignForm的设置信息
      obj = JSON.parse(localStorage.getItem("series-DATA"));
    } else {
      this.$router.replace({
        name: "CreateSeries",
        query: {
          // type: this.$route.type || "self-help",
          type: this.$route.type || "common",
          create: this.$route.type || "new",
        },
      });
    }

    if (this.$route.query.create === "new" || !this.$route.query.create) {
      /* 如果是创建一条龙*/
      this.campaignForm = obj.campaignForm;
      this.campaignNegativeKeyword = obj.campaignNegativeKeyword;
      this.appInfo = obj.appInfo;
      if (this.appInfo.devices.indexOf("iphone") === -1) {
        this.targeForm.deviceClassStr = "IPAD";
        this.deviceList = [
          {
            label: "仅限iPad",
            value: "IPAD",
          },
        ];
      }

      if (this.appInfo.devices.indexOf("ipad") === -1) {
        this.targeForm.deviceClassStr = "IPHONE";
        this.deviceList = [
          {
            label: "仅限iPhone",
            value: "IPHONE",
          },
        ];
      }

      if (!this.$route.query.type || this.$route.query.type === "self-help") {
        if (
          this.$route.query.serialId == "0" ||
          this.$route.query.serialId === null ||
          this.$route.query.serialId === undefined
        ) {
          this.campaignForm.serialName = "默认广告系列组";
        } else {
          this.getAllSerial();
        }
      }
    } else if (this.$route.query.create === "addGroup") {
      // 如果是添加广告组
      const obj1 = JSON.parse(JSON.stringify(obj.campaignForm));
      const str = obj1.countriesOrRegions.substring(
        1,
        obj1.countriesOrRegions.length - 1
      );
      const arr = str.split(",");
      this.campaignForm = {
        ...obj1,
        dailyBudgetAmountNub: obj1.dailyBudgetAmount * 1,
        adChannelType: obj1.adchannelType,
        countriesOrRegions: arr,
      };

      if (this.$store.state.user.timeZone === "UTC") {
        this.adGroupForm.startTime = moment()
          .utc()
          .add(2, "hour")
          .format("YYYY-MM-DD HH:mm");
      } else {
        this.adGroupForm.startTime = moment()
          .add(2, "hour")
          .format("YYYY-MM-DD HH:mm");
      }

      // 还原设备
      searchApps(this.campaignForm.adamId).then((res) => {
        this.appInfo = res.data.data[0];
        if (this.appInfo.devices.indexOf("iphone") == -1) {
          this.targeForm.deviceClassStr = "IPAD";
          this.deviceList = [
            {
              label: "仅限iPad",
              value: "IPAD",
            },
          ];
        }

        if (this.appInfo.devices.indexOf("ipad") == -1) {
          this.targeForm.deviceClassStr = "IPHONE";
          this.deviceList = [
            {
              label: "仅限iPhone",
              value: "IPHONE",
            },
          ];
        }
      });

      // 广告系列的长度
      if (obj1.campaignNegativeKeyWordsNub * 1 === 0) {
        this.campaignNegativeKeyword = [];
      } else {
        for (let i = 0; i < obj1.campaignNegativeKeyWordsNub * 1; i++) {
          this.campaignNegativeKeyword.push({});
        }
      }
    }

    // 获取储存的广告组设置信息
    if (localStorage.getItem("group-DATA")) {
      // 如果有储存参数
      const obj = JSON.parse(localStorage.getItem("group-DATA"));
      this.adGroupForm = obj.adGroupForm;
      this.negativeKeyword = obj.negativeKeyword;
      this.keywords = obj.keywords;
      this.targeForm = obj.targeForm;
      this.endTimeShow = obj.endTimeShow;

      if (this.targeForm.localArr.length) {
        this.locList = JSON.parse(JSON.stringify(this.targeForm.localArr));
        this.locVal = this.targeForm.localArr.map((item) => {
          return item.id;
        });
      } else {
        this.locList = [];
        this.locVal = [];
      }
    }
    if (!this.adGroupForm.startTime) {
      if (this.$store.state.user.timeZone === "UTC") {
        this.adGroupForm.startTime = moment()
          .utc()
          .add(2, "hour")
          .format("YYYY-MM-DD HH:mm");
        this.startTime.time = moment().utc().add(2, "hour").format("HH:mm");
      } else {
        this.adGroupForm.startTime = moment()
          .add(2, "hour")
          .format("YYYY-MM-DD HH:mm");
        this.startTime.time = moment().add(2, "hour").format("HH:mm");
      }
    }

    // 获取之前的广告系列设置信息
  },
  methods: {
    // 广告素材设备选择
    chooseDevice(data) {
      console.log(data);
    },
    // 自定义页面创建弹框
    createGroup() {
      this.$nextTick(() => {
        this.createGroupShow = true;
      });
    },
    // 获取全部广告系列组;
    async getAllSerial() {
      const obj = {
        currencyType: this.$store.state.user.unit,
        teamId: this.$store.state.team.teamId || "",
      };
      try {
        const res = await this.$store.dispatch("overview/getAllSerial", obj);
        if (res.data.code === 20000) {
          const arr = res.data.data;
          const index = arr.findIndex((item) => {
            return item.id === this.$route.query.serialId * 1;
          });
          this.campaignForm.serialName = arr[index].name;
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    },

    // 位置细分
    async getLocation(val) {
      if (val.length < 1) return false;
      const obj = {
        country: this.campaignForm.countriesOrRegions[0],
        search: val,
      };
      const res = await getSearchGeolocations(obj);
      if (res.data.code * 1 === 20000) {
        this.locList = [...res.data.data, ...this.targeForm.localArr];
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "服务器错误，请稍候刷新重试");
      }
    },

    async goToNext() {
      this.$refs["adGroupForm1"].validate(async (valid) => {
        if (valid) {
          // 判断开始日期  开始时间晚于现在的UTC时间？
          const nowUTCTime = moment().utc().format("YYYY-MM-DD HH:mm");

          let startFlag;
          if (this.$store.state.user.timeZone === "UTC") {
            startFlag = moment(this.adGroupForm.startTime).isAfter(nowUTCTime);
          } else {
            startFlag = moment(this.adGroupForm.startTime).isAfter(moment());
          }

          if (!startFlag) {
            if (this.$store.state.user.timeZone === "UTC") {
              this.adGroupForm.startTime = moment()
                .utc()
                .add(20, "minute")
                .format("YYYY-MM-DD HH:mm");
            } else {
              this.adGroupForm.startTime = moment()
                .add(20, "minute")
                .format("YYYY-MM-DD HH:mm");
            }
            startFlag = true;
          }

          let endTimeFlag = true;
          if (this.endTimeShow) {
            // 投放结束时间判断;如果有选择结束时间
            if (!this.adGroupForm.endTime) {
              this.$message.closeAll();
              this.$message.error("请选择投放结束时间");
              endTimeFlag = false;
              return;
            } else {
              // 开始时间晚于结束时间
              const falg = moment(this.adGroupForm.startTime)
                .add(1, "m")
                .isAfter(moment(this.adGroupForm.endTime));
              if (falg) {
                this.$message.closeAll();
                this.$message.error("投放结束时间必须晚于投放开始时间");
                endTimeFlag = false;
                return;
              } else {
                endTimeFlag = true;
              }
            }
          } else {
            this.adGroupForm.endTime = undefined;
            endTimeFlag = true;
          }

          if (startFlag && endTimeFlag) {
            // 获取分时段
            /*  if (this.campaignForm.adChannelType !== 'DISPLAY') {
                  this.targeForm.daypartInt = this.$refs['daypartBox'].computTime()
                } */
            // 去投放页面
            this.$router.push({
              name: "CreatePut",
              query: { ...this.$route.query },
            });
          }
        } else {
          this.$message.closeAll();
          this.$message({
            message: "请完善必填信息",
            type: "warning",
          });
        }
      });
    },
    // 返回上一步
    goToBefore() {
      this.$router.replace({
        name: "CreateSeries",
        query: { ...this.$route.query },
      });
      // if (
      //   this.$router.history.current.name === "CreateSeries" ||
      //   this.$route.query.create === "new"
      // ) {

      // } else {
      //   this.$router.replace({
      //     name: "seriesOverview",
      //     query: { ...this.$route.query },
      //   });
      // }
    },

    handSubAddGroup() {
      this.$refs["adGroupForm1"].validate(async (valid) => {
        if (valid) {
          const nowTime1 = moment().utc().format("YYYY-MM-DD HH:mm");

          let startTime1 =
            this.timeZone === "UTC"
              ? this.adGroupForm.startTime
              : moment(this.adGroupForm.startTime)
                  .utc()
                  .format("YYYY-MM-DD HH:mm");

          let endTime1;
          if (this.adGroupForm.endTime) {
            endTime1 =
              this.timeZone === "UTC"
                ? this.adGroupForm.endTime
                : moment(this.adGroupForm.endTime)
                    .utc()
                    .format("YYYY-MM-DD HH:mm");
          }

          if (!moment(startTime1).isAfter(nowTime1)) {
            startTime1 = moment()
              .utc()
              .add(20, "minute")
              .format("YYYY-MM-DD HH:mm:ss");
            if (this.timeZone === "UTC") {
              this.adGroupForm.startTime = startTime1;
            } else {
              this.adGroupForm.startTime = moment()
                .add(20, "minute")
                .format("YYYY-MM-DD HH:mm:ss");
            }

            // 检查一个 moment 是否在另一个 moment 之后
          }

          if (
            this.adGroupForm.endTime &&
            moment(this.adGroupForm.startTime)
              .add(1, "m")
              .isAfter(this.adGroupForm.endTime)
          ) {
            this.$message.closeAll();
            this.$message.error("投放结束时间必须晚于投放开始时间");
          } else {
            this.addLoading = true;
            // 获取分时段
            /* if (this.campaignForm.adChannelType !== 'DISPLAY') {
                this.targeForm.daypartInt = this.$refs['daypartBox'].computTime()
              } */

            const targeForm = JSON.parse(JSON.stringify(this.targeForm));
            const adGroupForm = JSON.parse(JSON.stringify(this.adGroupForm));
            const campaignForm = JSON.parse(JSON.stringify(this.campaignForm));

            if (!this.endTimeShow) {
              // 如果结束时间不显示
              this.adGroupForm.endTime = undefined;
            }

            if (!Array.isArray(targeForm.deviceClassStr)) {
              // 受众-设备
              if (targeForm.deviceClassStr.indexOf(",") !== -1) {
                // 设备转换成数组
                targeForm.deviceClassStr = targeForm.deviceClassStr.split(",");
              } else {
                targeForm.deviceClassStr = [targeForm.deviceClassStr];
              }
            }

            if (!Array.isArray(targeForm.genderStr)) {
              // 受众-性别转换
              if (targeForm.genderStr.indexOf(",") !== -1) {
                delete targeForm.genderStr; // 性别如果不限  则删除这个键值对
              } else {
                targeForm.genderStr = [targeForm.genderStr];
              }
            }

            if (targeForm.minMaxAge.minAge === "all") {
              // 设置年龄
              delete targeForm.minMaxAge;
            } else if (targeForm.minMaxAge.maxAge === 65) {
              delete targeForm.minMaxAge.maxAge;
            }
            if (
              targeForm.appDownloadersStr &&
              targeForm.appDownloadersStr !== "all"
            ) {
              // 如果填写当前app的appid,就代表只允许新用户下载；
              targeForm.appDownloadersStr = [campaignForm.adamId]; // 如果只能新用户下载，包裹起来
            } else {
              if (targeForm.appDownloadersStr) {
                delete targeForm.appDownloadersStr;
              } // 否则就不传这个键值对
            }

            if (!adGroupForm.endTime) {
              // 如果结束时间不显示
              adGroupForm.endTime = undefined;
            } else {
              adGroupForm.endTime = moment(endTime1).format(
                "YYYY-MM-DDTHH:mm:ss.000"
              );
            }
            adGroupForm.startTime = moment(startTime1).format(
              "YYYY-MM-DDTHH:mm:ss.000"
            ); // 设置开始时间;

            if (targeForm.daypartInt && targeForm.daypartInt.length === 0) {
              delete targeForm.daypartInt;
            }

            if (
              targeForm.localArr.length &&
              campaignForm.countriesOrRegions.length === 1
            ) {
              const localLity = [];
              const adminArea = [];

              targeForm.localArr.forEach((item) => {
                if (item.entity === "Locality") {
                  localLity.push(item.geolocationid);
                } else {
                  adminArea.push(item.geolocationid);
                }
              });
              if (localLity.length) {
                targeForm.locality = {
                  included: [...localLity],
                };
              }
              if (adminArea.length) {
                targeForm.adminArea = {
                  included: [...adminArea],
                };
              }
              delete targeForm.localArr;
            } else {
              delete targeForm.localArr;
            }

            // 总数据
            const advInfo = {
              campaign: {
                adChannelType: campaignForm.adChannelType,
              },
              adGroup: {
                ...adGroupForm,
                targetingDimensions: { ...targeForm },
              },
              orgId: this.$route.query.orgId || this.$route.query.orgid || "", // 自助投放时为空,
              uuid: this.$route.query.uuid || "", // 自助投放时为
              aId: this.$route.query.aId || this.$route.query.aid || "",
              userId: this.$store.state.user.userInfo.userId,
              campaignId: this.$route.query.campaignId,
              currencyType: this.$store.state.user.unit,
              teamId: this.$store.state.team.teamId || "",
            };

            if (this.$route.query.type === "self-help") {
              if (
                this.$route.query.serialId * 1 === 0 ||
                this.$route.query.serialId === undefined
              ) {
                advInfo.campaignGroupId = "";
              } else {
                advInfo.campaignGroupId = this.$route.query.serialId * 1;
              }
            }

            if (campaignForm.adChannelType === "SEARCH") {
              // 搜索结果时
              advInfo.negativeKeyword = this.negativeKeyword;
              advInfo.keywords = this.keywords;
            }
            const res = await addGroups({ ...advInfo });
            if (res.data.code && res.data.code === 20000) {
              this.addLoading = false;
              this.$message.closeAll();
              setTimeout(() => {
                this.$message({
                  message: "创建成功",
                  type: "success",
                });
                this.$router.go(-1);
              }, 1500);
            } else {
              this.addLoading = false;
              this.$message.closeAll();
              this.$message({
                message: "请完善必填信息",
                type: "warning",
              });
            }
          }
        } else {
          this.$message.closeAll();
          this.$message({
            message: "请完善必填信息",
            type: "warning",
          });
        }
      });
    },

    // 开始时间日期改变的时候
    changeStartTime(time) {
      this.adGroupForm.startTime =
        this.adGroupForm.startTime.slice(0, 11) + time;
    },

    // 结束时间日期改变的时候
    changeEndTime(time) {
      this.adGroupForm.endTime = this.adGroupForm.endTime.slice(0, 11) + time;
    },
    // 广告组投放关键词改变
    handleSubKey(data) {
      this.keywords = data;
    },
    // 广告组否定关键词改变
    handleSubNegKey(data) {
      this.negativeKeyword = data;
    },

    // 位置细分开始发生改变
    handleLocChange(data) {
      this.targeForm.localArr = [];
      if (!data.length) {
        this.targeForm.localArr = [];
      } else {
        data.forEach((item) => {
          const index = this.locList.findIndex((v) => {
            return v.id === item;
          });
          this.targeForm.localArr.push(this.locList[index]);
        });
      }
    },
    onInput() {
      this.$forceUpdate();
    },
  },
};
</script>

<style lang="scss" scoped="true">
// 广告素材样式开始
.sc_content {
  width: 820px;
  .sc_content_flex {
    display: flex;
    width: 820px;
    .sc_content_div {
      .sc_content_div_select {
        border: 1px solid #e0e2e7;
        margin-top: 12px;
        width: 400px;
        height: 80px;
        border-radius: 2px;
        p {
          margin-left: 12px;
          line-height: 25px;
          margin-top: 10px;
        }
      }
    }
    .sc_content_div_right {
      margin-left: 100px;
    }
  }
}
// 广告素材样式结束
.automatch {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
  width: 486px;
  ::v-deep .label {
    padding-bottom: 0px !important;
  }
}

.el-collapse {
  border: none;
}

.shou-zhong-box.el-collapse::v-deep .el-collapse-item__header {
  height: auto;
  line-height: 14px;
  border: none;
  border-bottom: none !important;
}

.shou-zhong-box.el-collapse::v-deep .el-collapse-item__content {
  padding: 0;
}

.shou-zhong-box.el-collapse::v-deep .el-collapse-item__wrap {
  border: none;
}

.shou-zhong-box ::v-deep.el-collapse-item__arrow {
  margin: 0 8px;

  &.el-icon-arrow-right:before {
    content: "\e791" !important;
  }
}

.shou-zhong-box ::v-deep .timeBox {
  .el-input__prefix {
    display: none;
  }
}
</style>
